﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Xml.Linq;

namespace INTREPWEB.Controllers
{
    public class TempoRealController : Controller
    {
        public ActionResult Index()
        {
            
                return View();         
        }

        public ActionResult Grafico()
        {
            var filename = "~/totalporhora.xml";
            var caminho = HttpContext.Server.MapPath(filename);

            XDocument doc;

            try
            {
                doc = XDocument.Load(caminho);

                var balancas = from c in doc.Root.Elements()
                               select c;

                var balancaslist = new List<KeyValuePair<string, int[]>>();
                var horas = new string[10];

                for (int i = 0; i < balancas.Count(); i++)
                {
                    var qt_pesagens = balancas.ElementAt(i).Elements().Count();
                    if (qt_pesagens > 10)
                        qt_pesagens = 10;
                    var valores = new int[10];

                    for (int j = 0; j < qt_pesagens; j++)
                    {
                        horas[j] = balancas.ElementAt(i).Elements().ElementAt(j).Attribute("Hora").Value.TrimStart('0');
                        valores[j] = Int32.Parse(balancas.ElementAt(i).Elements().ElementAt(j).Value);
                    }
                    var balanca = new KeyValuePair<string, int[]>(balancas.ElementAt(i).Attribute("Id").Value.TrimStart('0'), valores);

                    balancaslist.Add(balanca);
                }

                ViewBag.Pesagens = new KeyValuePair<string[], List<KeyValuePair<string, int[]>>>(horas, balancaslist);

                ViewBag.Teste = balancas.Count();
            }
            catch (FileNotFoundException)
            {
                ViewBag.Error = "Arquivo não encontrado!";
                return View("Error");
            }

            if (doc != null)
            {
                return PartialView();
            }
            else
            {
                ViewBag.Error = "Sem dados para exibir!";
                return View("Error");
            }  
        }
    }
}
